<?php

namespace App\Morefun\Prize;

use App\Entities\ActivityPrize;
use App\Entities\DrawRecord;
use Illuminate\Container\Container;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Ramsey\Uuid\Uuid;

class DrawRecordSynchronizer
{
    const REDIS_RECORD_KEY = 'draw:records';
    /**
     * @var \Redis
     */
    protected $redis;

    public function sync()
    {
        $connect = DrawRecord::query();

        /**
         * @var Builder
         */
        $binder = Container::getInstance()->make('db')->table('activity_prizes');

        while (($record = $this->redis()->lPop(self::REDIS_RECORD_KEY)) !== null) {
            $log = json_decode($record, true);

            if (!$log) {
                continue;
            }

            $at = date('Y-m-d H:i:s', Arr::get($log, 'created_at', 0));
            $activityId = Arr::get($log, 'activity_id', '');
            $prizeId = Arr::get($log, 'prize_id', '');
            $openid = Arr::get($log, 'open_id', '');
            $uniqueid = md5($openid);
            $connect->insert([
                'id' => Arr::get($log, 'id'),
                'activity_id' => $activityId,
                'prize_id' => $prizeId,
                'openid' => $uniqueid,
                'coupon' => Arr::get($log, 'coupon', ''),
                'extends' => '{}',
                'created_at' => $at,
                'updated_at' => $at,
            ]);

            // 减少库存
            $binder->where('activity_id', $activityId)
                ->where('prize_id', $prizeId)
                ->decrement('surplus');

            usleep(3000);
        }
    }

    protected function redis()
    {
        if (!$this->redis) {
            $this->redis = Container::getInstance()->make('redis');
        }

        return $this->redis;
    }
}
